package com.excellence.controller;

import com.alibaba.fastjson.JSON;
import com.excellence.datamodel.Result;
import okhttp3.*;
import okhttp3.RequestBody;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/chatAi")
public class ChatAiController {
    public static final String API_KEY = "kR2VAr2WDBbi5CEGzN9O0TwB";
    public static final String SECRET_KEY = "u4nm4wD6xEHpTLKl7T0dcUW5sGzcszV8";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(300, TimeUnit.SECONDS).readTimeout(300, TimeUnit.SECONDS).writeTimeout(300, TimeUnit.SECONDS).build();

    @GetMapping()
    public Result getContent(String text) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"messages\":[{\"role\":\"user\",\"content\":\"" + text + "\"}],\"temperature\":0.95,\"top_p\":0.8,\"penalty_score\":1,\"disable_search\":false,\"enable_citation\":false}");
        //鉴权签名（Access Token）一个月会过期，需要重新获取
        String accessToken = "24.1a703f2b1da281c2e5740395b503eb0d.2592000.1717689047.282335-42117832";
        System.out.println(accessToken);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSON res = (JSON) JSON.parse(response.body().string());
        System.out.println(res);
        return Result.success(res);
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}